package cn.iocoder.yudao.module.call.service.ivrknowledgeissuevoice;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.call.util.TmtUtil;
import cn.iocoder.yudao.module.call.util.TtsUtil;
import cn.iocoder.yudao.module.system.api.extend.ExtendApi;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import cn.iocoder.yudao.module.call.controller.admin.ivrknowledgeissuevoice.vo.*;
import cn.iocoder.yudao.module.call.dal.dataobject.ivrknowledgeissuevoice.IvrKnowledgeIssueVoiceDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.call.dal.mysql.ivrknowledgeissuevoice.IvrKnowledgeIssueVoiceMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.call.enums.ErrorCodeConstants.*;

/**
 * ivr-知识库回答语音 Service 实现类
 *
 * @author 数创万维
 */
@Service
@Validated
public class IvrKnowledgeIssueVoiceServiceImpl implements IvrKnowledgeIssueVoiceService {

    @Resource
    private IvrKnowledgeIssueVoiceMapper ivrKnowledgeIssueVoiceMapper;
    @Resource
    private ExtendApi extendApi;
    @Override
    public Long createIvrKnowledgeIssueVoice(IvrKnowledgeIssueVoiceSaveReqVO createReqVO) {
        // 插入
        InputStream inputStream = null;
        try {
            if (StringUtils.isNotEmpty(createReqVO.getRecordPath())) {
                inputStream = getFileFromUrl(createReqVO.getRecordPath());
                // 将文件转换为字节数组
                byte[] fileBytes = convertStreamToBytes(inputStream);
                // 将字节数组转换为 Base64 字符串
                String base64String = encodeToBase64(fileBytes);
                // 输出 Base64 字符串
                String content = TmtUtil.tengXunTmt(base64String);
                createReqVO.setRecordContent(content);
            }
            createReqVO.setRecordContent(createReqVO.getRecordDescription());
            IvrKnowledgeIssueVoiceDO ivrKnowledgeIssueVoice = BeanUtils.toBean(createReqVO, IvrKnowledgeIssueVoiceDO.class);
            ivrKnowledgeIssueVoiceMapper.insert(ivrKnowledgeIssueVoice);
            return ivrKnowledgeIssueVoice.getId();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 返回
    }

    // 从 URL 获取文件输入流
    private static InputStream getFileFromUrl(String fileUrl) throws Exception {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000); // 设置连接超时时间
        connection.setReadTimeout(5000);    // 设置读取超时时间
        return connection.getInputStream();
    }

    // 将输入流转换为字节数组
    private static byte[] convertStreamToBytes(InputStream inputStream) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        return byteArrayOutputStream.toByteArray();
    }

    // 将字节数组编码为 Base64 字符串
    private static String encodeToBase64(byte[] data) {
        return Base64.getEncoder().encodeToString(data);
    }

    @Override
    public Integer issueSynthesisVoice(Long id, String voiceType) {
        IvrKnowledgeIssueVoiceDO ivrKnowledgeIssueVoiceDO = ivrKnowledgeIssueVoiceMapper.selectById(id);
        byte[] baiDuTtsByte = TtsUtil.getKeDaXunFeiTtsBasicUrl(ivrKnowledgeIssueVoiceDO.getRecordContent(), voiceType);
        String baiDuTtsByteString = Base64.getEncoder().encodeToString(baiDuTtsByte);
        Map<String, Object> params = new HashMap<String, Object>() {{
            put("ttsByte", baiDuTtsByteString);
            put("type", "tts");
        }};
        extendApi.setDomain("");
        JSONObject agentState = extendApi.request("/index/pcmToWave", JSONUtil.toJsonStr(params));
        String filePath = agentState.getStr("filePath");
        String localPath = agentState.getStr("localPath");
        ivrKnowledgeIssueVoiceDO.setRecordPath(filePath);
        ivrKnowledgeIssueVoiceDO.setLocalPath(localPath);
        int ret = ivrKnowledgeIssueVoiceMapper.updateById(ivrKnowledgeIssueVoiceDO);
        return ret;
    }

    @Override
    public void updateIvrKnowledgeIssueVoice(IvrKnowledgeIssueVoiceSaveReqVO updateReqVO) {
        // 校验存在
        validateIvrKnowledgeIssueVoiceExists(updateReqVO.getId());
        // 更新
        updateReqVO.setRecordPath(null);
        updateReqVO.setLocalPath(null);
        IvrKnowledgeIssueVoiceDO updateObj = BeanUtils.toBean(updateReqVO, IvrKnowledgeIssueVoiceDO.class);
        ivrKnowledgeIssueVoiceMapper.updateById(updateObj);
    }

    @Override
    public void deleteIvrKnowledgeIssueVoice(Long id) {
        // 校验存在
        validateIvrKnowledgeIssueVoiceExists(id);
        // 删除
        ivrKnowledgeIssueVoiceMapper.deleteById(id);
    }

    private void validateIvrKnowledgeIssueVoiceExists(Long id) {
        if (ivrKnowledgeIssueVoiceMapper.selectById(id) == null) {
            throw exception(IVR_KNOWLEDGE_ISSUE_VOICE_NOT_EXISTS);
        }
    }

    @Override
    public IvrKnowledgeIssueVoiceDO getIvrKnowledgeIssueVoice(Long id) {
        return ivrKnowledgeIssueVoiceMapper.selectById(id);
    }

    @Override
    public PageResult<IvrKnowledgeIssueVoiceDO> getIvrKnowledgeIssueVoicePage(IvrKnowledgeIssueVoicePageReqVO pageReqVO) {
        return ivrKnowledgeIssueVoiceMapper.selectPage(pageReqVO);
    }

}